import cv2
import numpy as np
def nothing(x):
    pass


img_raw = cv2.imread('./images/0828/6068A_1_24.240.jpeg')

img_raw = cv2.resize(img_raw,(600,800))
gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)

cv2.namedWindow("Trackbars")
cv2.createTrackbar("dp", "Trackbars", 1, 3, nothing)
cv2.createTrackbar("minDist", "Trackbars", 5, 255, nothing)
cv2.createTrackbar("param1", "Trackbars", 100, 255, nothing)
cv2.createTrackbar("param2", "Trackbars", 30, 255, nothing)
cv2.createTrackbar("minRadius", "Trackbars", 2, 255, nothing)
cv2.createTrackbar("maxRadius", "Trackbars", 50, 255, nothing)
while True:
    blur = cv2.GaussianBlur(gray, (3, 3), 0)
    # blur = gray.copy()

    dp = cv2.getTrackbarPos("dp", "Trackbars")
    minDist = cv2.getTrackbarPos("minDist", "Trackbars")
    param1 = cv2.getTrackbarPos("param1", "Trackbars")
    param2 = cv2.getTrackbarPos("param2", "Trackbars")
    minRadius = cv2.getTrackbarPos("minRadius", "Trackbars")
    maxRadius = cv2.getTrackbarPos("maxRadius", "Trackbars")

    circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, dp, minDist,
                               param1 = param1, param2 = param2, minRadius = minRadius, maxRadius = maxRadius)

    # circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, minDist,
    #                            param1=param1, param2=param2,
    #                            minRadius=int(1/40*min(img_raw.shape[0],img_raw.shape[1])),
    #                            maxRadius=int(1/8*max(img_raw.shape[0],img_raw.shape[1])))

    # circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, 50,
    #                            param1=100, param2=30,
    #                            minRadius=int(1/20*min(img_raw.shape[0],img_raw.shape[1])),
    #                            maxRadius=int(1/8*max(img_raw.shape[0],img_raw.shape[1])))

    if circles is not None:
        print("First", len(circles))

        circles = np.uint16(np.around(circles))
        print("Second", len(circles))

        if (len(circles) < 300):
            for i in circles[0, :]:
                # draw the outer circle
                cv2.circle(blur, (i[0], i[1]), i[2], (0, 255, 0), 2)
                # draw the center of the circle
                cv2.circle(blur, (i[0], i[1]), 2, (0, 0, 255), 3)

            cv2.imshow("frame", blur)

        else:
            print("Too many circles.")
    key = cv2.waitKey(1)
    if key == 27:
        break

cv2.destroyAllWindows()